import { useDownloadFile } from "@/service/dowload";
import { baseURL } from "@/service/request/config";
import { ThemeProvider } from "@emotion/react";
import DirectionsIcon from "@mui/icons-material/Directions";
import MenuIcon from "@mui/icons-material/Menu";
import { createTheme } from "@mui/material";
import Box from "@mui/material/Box";
import Divider from "@mui/material/Divider";
import IconButton from "@mui/material/IconButton";
import InputBase from "@mui/material/InputBase";
import Paper from "@mui/material/Paper";
import type { TableProps } from "antd";
import { Button, Space, Table, Tooltip, message } from "antd";
import Image from "next/image";
import { useState } from "react";

import v1 from "../../../../public/download.svg";
interface DataType {
  key: string;
  name: string;
  path: string;
  id: number;
  status: string;
}

export default function DownloadRight(props: any) {
  const {
    dataSource,
    searchText,
    setSearchText,
    downloadFileLoading,
    total,
    setPage,
    filterType,
    page,
  } = props;
  const defaultTheme = createTheme({ palette: { mode: "light" } });
  const { mutateAsync: downFile, isPending: downloadPending } =
    useDownloadFile();

  const [fileId, setFileId] = useState(0);
  const handleDownloadFile = async (id: number) => {
    setFileId(id);
    try {
      await downFile({ filter_type: filterType, file_id: id });
      const link = document.createElement("a");
      link.target = "_self";
      link.href = `${baseURL}/download/${filterType}/${id}/download/`;
      link.click();
      link.remove();
    } catch (err: any) {
      message.error("该文件不存在");
    } finally {
      setFileId(0);
    }
  };

  const columns: TableProps<DataType>["columns"] = [
    {
      title:
        filterType == "bacteria"
          ? "Species"
          : filterType == "all"
          ? "Name"
          : "Host species",
      dataIndex: "name",
      key: "name",
      ellipsis: true,
      width: "300px",
      render: (text) => (
        <div
          style={{
            overflow: "hidden",
            textOverflow: "ellipsis",
            whiteSpace: "nowrap",
          }}
        >
          <Tooltip placement="top" title={text}>
            <a>{text.replace("_", " ")}</a>
          </Tooltip>
        </div>
      ),
    },
    {
      title: "Tax_id",
      dataIndex: "tax_id",
      key: "tax_id",
      render: (text) => (
        <div
          style={{
            overflow: "hidden",
            textOverflow: "ellipsis",
            whiteSpace: "nowrap",
            width: "100px",
            paddingLeft: "7px",
          }}
        >
          <span>{text || "-"}</span>
        </div>
      ),
    },
    // {
    //   title: "Status",
    //   key: "status",
    //   dataIndex: "status",
    //   render: (_) => (
    //     <>
    //       <Tag color={"green"}>Available</Tag>
    //     </>
    //   ),
    // },
    {
      title: "Download",
      key: "action",
      render: (_, record) => (
        <Space size="middle" onClick={() => handleDownloadFile(record.id)}>
          <Button loading={record.id == fileId && downloadPending}>
            <Image
              src={v1}
              width={12}
              height={12}
              alt="Picture of the author"
            />
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <ThemeProvider theme={defaultTheme}>
      <Box
        sx={{
          p: "2px 16px",
          display: "flex",
          flexDirection: "column",
          flex: 1,
        }}
      >
        <Paper
          sx={{
            p: "2px 4px",
            display: "flex",
            alignItems: "center",
          }}
        >
          <IconButton sx={{ p: "10px" }} aria-label="menu">
            <MenuIcon />
          </IconButton>
          <InputBase
            sx={{ ml: 1, flex: 1 }}
            placeholder={"Search"}
            inputProps={{ "aria-label": "search google maps" }}
            onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
              setSearchText(event.target.value);
            }}
            value={searchText}
          />
          {/* <IconButton
            type="button"
            sx={{ p: "10px" }}
            aria-label="search"
            onClick={() => handleSearch()}
          >
            <SearchIcon />
          </IconButton> */}
          <Divider sx={{ height: 28, m: 0.5 }} orientation="vertical" />
          <IconButton
            color="primary"
            sx={{ p: "10px" }}
            aria-label="directions"
            onClick={() => {
              setSearchText(() => "");
            }}
          >
            <DirectionsIcon />
          </IconButton>
        </Paper>

        <Box
          component={"div"}
          sx={{
            display: "flex",
            flexDirection: "column",
            marginTop: "1rem",
          }}
        >
          <Table
            pagination={{
              pageSize: 10,
              total: total,
              onChange: (page: number, pageSize: number) => {
                setPage(page);
              },
              current: page,
              showSizeChanger: false,
            }}
            scroll={{ y: 400 }}
            columns={columns}
            dataSource={dataSource || []}
            loading={downloadFileLoading}
          />
        </Box>
      </Box>
    </ThemeProvider>
  );
}
